<template>
  <el-tooltip :content="content" :disabled="disabled" placement="top">
    <span
      class="m-svg-icon-tooltip"
      :class="{ pointer: pointer, 'disabled-container': disabled }"
      >
      <img v-if="imgUrl" :src="imgUrl" v-bind="$attrs" @click="click" />
    </span>
  </el-tooltip>
</template>

<script setup lang="ts">
import { computed, h } from 'vue'
import { ElMessageBox } from 'element-plus'

defineOptions({
  name: 'MSvgIconTooltip'
})

const props = withDefaults(
  defineProps<{
    name?: string
    size?: number | string
    disabled?: boolean
    pointer?: boolean
    content?: string
  }>(),
  {
    disabled: false,
    pointer: true
  }
)

const emits = defineEmits(['click'])
const imgUrl = computed(() => {
  return props.name && getImageUrl(props.name)
})

// TODO: https://cn.vitejs.dev/guide/assets
function getImageUrl(name: string) {
  return new URL(`../../../assets/svg/${name}.svg`, import.meta.url).href
}

const click = (e) => {
  if (props.name === 'del') {
    ElMessageBox.confirm(
      h('div', [
        h('div', '确定要删除选择的数据吗？'),
        h('div', '数据将被永久删除，且无法恢复，请确认您的操作。')
      ]),
      '温馨提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(() => {
        emits('click')
      })
      .catch(() => {})
  } else {
    emits('click')
  }
}
</script>

<style lang="scss" scoped>
.m-svg-icon-tooltip {
  display: inline-flex;
  justify-content: center;
  vertical-align: middle;
  margin-right: 16px;
  &.pointer {
    cursor: pointer;
  }
  &.disabled-container {
    filter: grayscale(1);
    cursor: not-allowed;
  }
}
</style>
